<?php

namespace app\api\controller;

include '../vendor/qrcode/QRcode.php';
use app\admin\model\config\Subtitle;
use app\common\controller\Api;
use app\common\helpers\ImageUtil;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use myqrcode\qrcode\QRcode;
use think\Config;
use think\Log;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'wxLogin','rollindex', 'getWxPhone','register', 'resetpwd', 'changeemail', 'changemobile', 'third','getRut'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }


    /**
     * 用户登录
     *
     */
    public function wxLogin()
    {
        $validate = new \think\Validate([
            ['code', 'require', 'code不能为空'],
            ['avatar', 'require', '头像不能为空'],
            ['nickname', 'require', '昵称不能为空'],
//            ['mobile', 'require', '电话号码不能为空'],
        ]);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $code = $this->request->param("code");
        $result = getOpenid($code);
        if (!isset($result['openid'])) {
            $this->error('请求错误', $result);
        }
        $data = [
            "nickname" => $this->request->param("nickname"),
            "avatar" => $this->request->param("avatar"),
//            "username"=> $this->request->param("mobile"),
//            "mobile"=> $this->request->param("mobile"),
        ];
        $inviter_id = $this->request->post('inviter_id');
        if($inviter_id){
            $inviter = \app\common\model\User::get($inviter_id);
            if($inviter){
                $data['inviter_id'] = $inviter_id;
                $data['inviter_one_uid'] = $inviter['one_uid'];
            }
        }
        $ret = $this->auth->wx_login($data, $result['openid'], $result['session_key']);
        if ($ret) {
            $user = $this->auth->getUserinfo();
            $user2 = \app\common\model\User::get($user["id"]);

            $userinfo = [
                "id" => $user["id"],
                "nickname" => $user["nickname"],
                "avatar" => ImageUtil::handle($user["avatar"]),
                "status" => $user2["status"],
                "mobile" => $user["mobile"],
                "member_expire_time"=>$user2['member_expire_time'],
                "token" => $user["token"],
                "lvl"=>3
            ];
            if($user2['is_tk'] == 1){
                $userinfo['lvl']= 2;
            }
            if($user2['member_expire_time'] > date('Y-m-d H:i:s')){
                $userinfo['lvl']= 1;
            }
            $this->success(__('Logged in successful'), $userinfo);
        } else {
            $this->error($this->auth->getError());
        }
    }


    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 获取用户信息
     * */
    public function member()
    {
        $user = $this->auth->getUser();
        $info = \app\common\model\User::field("id,nickname,avatar,mobile,money,is_tk,member_expire_time")->where(["id" => $user["id"]])->find();
        $info['lvl']= 3;
        if($info) {
            $info['avatar']= ImageUtil::handle($info['avatar']);
            if($info['is_tk'] == 1){
                $info['lvl']= 2;
            }
            if($info['member_expire_time'] > date('Y-m-d H:i:s')){
                $info['lvl']= 1;
            }
        }
        $this->success("成功", $info);
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }


    /**
     * 获取用户微信手机
     * @throws \think\Exception
     */
    public function getWxPhone()
    {
        $tmp = getAccessToken();
        $token = $tmp["access_token"];
        $data['code'] = input('code');
        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$token";
        $info = \fast\Http::post($url,json_encode($data),'json');
        // 一定要注意转json，否则汇报47001错误
        $tmpinfo = json_decode($info,true);
        if ($tmpinfo["errcode"]  == 0) {
            $this->success(__('Logged in successful'), ['mobile'=>$tmpinfo["phone_info"]["purePhoneNumber"],]);
        } else {
            $this->error($tmpinfo["errcode"] );
        }
    }

    /**
     * 会员推荐好友
     */
    public function inviteFriends()
    {
        $user = $this->auth->getUser();
        $path ='uploads/yq_img/';
        if(!file_exists($path)){
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($path,0777,true);
        }
        //设置二维码文件名
        $filename = $path.$user['openid'].'_'.$user['id'].'.png';
        if(!file_exists($filename)){
            QRcode::png('https://mdnc.westts.cn/pages/tabBar/home/home?inviter_id='.$user['id'], $filename, 'L', 4, 2);
            ob_get_contents();
            ob_end_clean();
        }
        $gData['pic'] = 'assets/web_img/p2.png';
        $this->createSharePng($gData, $filename,'/'.$path.$user['openid'].'_'.$user['id'].'_hb.png');
        $this->success('邀请图片', [
            'img'=>ImageUtil::handle('/'.$filename),
            'img_hb'=>ImageUtil::handle('/'.$path.$user['openid'].'_'.$user['id'].'_hb.png'),
        ]);
    }


    function createSharePng($gData, $codeName = "", $fileName = '')
    {
        //创建画布
        $im = imagecreatetruecolor(1000, 1500);
        //填充画布背景色
        $color = imagecolorallocate($im, 255, 255, 255);
        imagefill($im, 0, 0, $color);
        //商品图片
        list($g_w, $g_h) = getimagesize($gData['pic']);
        $goodImg = $this->createImageFromFile($gData['pic']);
        imagecopyresized($im, $goodImg, 0, 0, 0, 0, 1000, 1500, $g_w, $g_h);
        $path = dirname(dirname(dirname(__DIR__))).'/public';
        //二维码
        list($code_w, $code_h) = getimagesize($codeName);
        $codeImg = $this->createImageFromFile($codeName);
        imagecopyresized($im, $codeImg, 352, 748, 0, 0, 296, 296, $code_w, $code_h);
        if ($fileName) {
            $result = imagejpeg($im,   $path.$fileName);
            //释放空间
            imagedestroy($im);
            imagedestroy($goodImg);
            imagedestroy($codeImg);
            return $result;
        } else {
            Header("Content-Type: image/png");
            $result = imagepng($im);
            //释放空间
            imagedestroy($im);
            imagedestroy($goodImg);
            imagedestroy($codeImg);
            return $result;
        }
    }



    function createImageFromFile($file)
    {
        $fileSuffix = pathinfo($file, PATHINFO_EXTENSION);
        if (!$fileSuffix) return false;
        switch ($fileSuffix) {
            case 'jpeg':
                $theImage = @imagecreatefromjpeg($file);
                if (!$theImage) {
                    $theImage = @imagecreatefromstring(file_get_contents($file));
                }
                break;
            case 'jpg':
                $theImage = @imagecreatefromjpeg($file);
                if (!$theImage) {
                    $theImage = @imagecreatefromstring(file_get_contents($file));
                }
                break;
            case 'png':
                $theImage = @imagecreatefrompng($file);
                if (!$theImage) {
                    $theImage = @imagecreatefromstring(file_get_contents($file));
                }
                break;
            case 'gif':
                $theImage = @imagecreatefromgif($file);
                if (!$theImage) {
                    $theImage = @imagecreatefromstring(file_get_contents($file));
                }
                break;
            default:
                $theImage = @imagecreatefromstring(file_get_contents($file));
                break;
        }
        return $theImage;
    }






}
